package com.heima;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class Adder {
    static AtomicLong a = new AtomicLong();
    static LongAdder b = new LongAdder();
    static int threadNum = Runtime.getRuntime().availableProcessors();
    static int countMax = 10_0000;

    public static void main(String[] args) {
        intAdder();
        intStripedAdder();
    }

    private static void intAdder() {
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(() -> {
                for (int count = 0; count < countMax; count++) {
                    a.incrementAndGet();
                }
            });
            threadList.add(thread);
        }

        long start = System.nanoTime();
        threadList.forEach(Thread::start);
        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println((end - start) + "count=" + a);
    }


    private static void intStripedAdder() {
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(() -> {
                for (int count = 0; count < countMax; count++) {
                    b.increment();
                }
            });
            threadList.add(thread);
        }
        long start = System.nanoTime();

        threadList.forEach(Thread::start);
        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println((end - start) + "count=" + b);
    }
}
